import { Component } from 'react';
import { Button, Card, Form, Input, Checkbox, message } from 'antd';
import styles from './index.module.scss';
import logoSrc from 'assets/logo.png';
import { loginApi } from 'api/user';
import { setToken } from 'utils/storage';

export default class Login extends Component {
  handleFinish = async (values) => {
    // console.log(values);
    try {
      const res = await loginApi(values);
      // localStorage.setItem('geek-token', res.data.token);
      setToken(res.data.token);
      message.success('登录成功！', 1);
      this.props.history.push('/layout');
    } catch (error) {
      // console.dir(error);
      if (error.response) {
        message.warn(error.response.data.message, 1);
      }
    }
  };
  render() {
    return (
      <div className={styles.login}>
        <Card className="login-container">
          <img className="login-logo" src={logoSrc} alt="" />
          {/* 表单 */}
          <Form
            size="large"
            validateTrigger="onBlur"
            autoComplete="off"
            onFinish={this.handleFinish}
            initialValues={{
              mobile: '13911111111',
              code: '246810',
              agree: true,
            }}
          >
            <Form.Item
              name="mobile"
              rules={[
                {
                  required: true,
                  message: '手机号不能为空',
                },
                {
                  pattern: /^1[3-9]\d{9}$/,
                  message: '请输入11位手机号码',
                },
              ]}
            >
              <Input placeholder="请输入手机号" />
            </Form.Item>

            <Form.Item
              name="code"
              rules={[
                {
                  required: true,
                  message: '验证码不能为空',
                },
                {
                  min: 6,
                  max: 6,
                  message: '请输入6位验证码',
                },
              ]}
            >
              <Input placeholder="请输入验证码" />
            </Form.Item>

            <Form.Item
              name="agree"
              valuePropName="checked"
              rules={[
                {
                  validator: (_, value) =>
                    value
                      ? Promise.resolve()
                      : Promise.reject(new Error('请阅读并勾选')),
                },
              ]}
            >
              <Checkbox>我已阅读并同意[用户协议]和[隐私条款]</Checkbox>
            </Form.Item>

            <Form.Item>
              <Button type="primary" htmlType="submit" block>
                登录
              </Button>
            </Form.Item>
          </Form>
        </Card>
      </div>
    );
  }
}
